<template>
	<el-card>
		<el-row :gutter="15" justify="space-between">
			<el-col :span="13">
				<div style="display: flex; flex-direction: row">
					<el-avatar :size="60" :src="userStore.user.avatar" />
					<div style="display: flex; flex-direction: column; margin-left: 20px; line-height: 30px">
						<h1>{{ welcomeSentence }}</h1>
						<p style="color: #333">{{ dayInfo }}</p>
						<div>
							<div class="weather">
								<iframe
									width="100%"
									height="50"
									src="//i.tianqi.com/index.php?c=code&id=12&icon=1&num=3&site=12"
									@click="weatherClick"
									style="border: none"
								></iframe>
							</div>
							<span class="left-content user-header">
								<a class="sentence" target="_blank">{{ heartSentence }} </a>
							</span>
						</div>
					</div>
				</div>
			</el-col>
			<el-col :span="3" style="text-align: center">
				<el-statistic title="项目总数" :value="projectValue" />
			</el-col>
			<el-col :span="3" style="text-align: center">
				<el-statistic title="在途项目" :value="uncompleteValue" />
			</el-col>
			<el-col :span="3" style="text-align: center">
				<el-statistic :value="completeValue">
					<template #title>
						<div style="display: inline-flex; align-items: center">已完成项目</div>
					</template>
					<template #suffix>/{{ source }}</template>
				</el-statistic>
			</el-col>
		</el-row>
	</el-card>

	<div class="home-image">
		<el-space fill wrap :fill-ratio="28" style="width: 100%">
			<el-card style="width: 600px">
				<template #header>
					<div class="card-header">
						<span>项目各环节统计</span>
					</div>
				</template>
				<div style="height: 420px; display: flex; justify-content: center">
					<div ref="main" style="width: 100%; height: 420px"></div>
				</div>
			</el-card>
		</el-space>

		<el-card>
			<el-tabs v-model="active">
				<el-tab-pane label="环节超时限项目列表" name="first">
					<el-table v-loading="tableLoading" :data="tableData" show-overflow-tooltip style="width: 100%">
						<el-table-column prop="projectCode" label="项目编码" width="150" />
						<el-table-column prop="projectName" label="项目名称" width="310" />
						<el-table-column prop="stepName" label="超时环节" />
						<el-table-column prop="duration" label="环节时长" />
						<el-table-column prop="weeklyProgress" label="本周进度" />
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store/modules/user'
import { useTransition } from '@vueuse/core'
import { computed, onMounted, ref } from 'vue'
import { Solar, Lunar } from 'lunar-javascript'
import _ from 'lodash'
import heartSentenceArray from './heart-sentence'
import { useStateCountApi, useProjectCountApi, useProjectTimeOutApi } from '@/api/project/info'
import * as echarts from 'echarts'

const userStore = useUserStore()
const stateCount = ref({} as any)
const projectCount = ref({} as any)
const projectTimeOutList = ref({} as any)
const tableData = ref([])
const tableLoading = ref(false)

const descLoading = ref(false)
const source = ref(0)
const projectcompleteCount = ref(0)
const projectUncompleteCount = ref(0)
const projectValue = useTransition(source, {
	duration: 1500
})
const completeValue = useTransition(projectcompleteCount, {
	duration: 1500
})
const uncompleteValue = useTransition(projectUncompleteCount, {
	duration: 1500
})

const weatherClick = e => {
	e.preventDefault()
}

// 欢迎语
const welcomeSentence = computed(() => {
	let sentence = ''
	let now = new Date().getHours()
	if (now > 0 && now <= 6) {
		sentence = '午夜好，'
	} else if (now > 6 && now <= 11) {
		sentence = '早上好，'
	} else if (now > 11 && now <= 14) {
		sentence = '中午好，'
	} else if (now > 14 && now <= 18) {
		sentence = '下午好，'
	} else {
		sentence = '晚上好，'
	}
	return sentence + userStore.user.realName
})

// 日期、节日、节气
const dayInfo = computed(() => {
	// 阳历
	let solar = Solar.fromDate(new Date())
	let day = solar.toString()
	let week = solar.getWeekInChinese()
	// 阴历
	let lunar = Lunar.fromDate(new Date())
	let lunarMonth = lunar.getMonthInChinese()
	let lunarDay = lunar.getDayInChinese()
	// 节气
	let jieqi = lunar.getPrevJieQi().getName()
	let next = lunar.getNextJieQi()
	let nextJieqi = next.getName() + ' ' + next.getSolar().toYmd()

	return `${day} 星期${week}，农历${lunarMonth}${lunarDay}（当前${jieqi}，${nextJieqi} ）`
})

// 毒鸡汤
const heartSentence = computed(() => {
	return heartSentenceArray[_.random(0, heartSentenceArray.length - 1)]
})

const active = ref('first')

onMounted(async () => {
	try {
		await init()
	} catch (error) {
		console.error('初始化组件时发生错误:', error)
	}
})

const main = ref(null)

// 初始化数据和图表
const init = async () => {
	try {
		descLoading.value = true
		// 并行获取所有必要的数据
		const responses = await Promise.all([useProjectCountApi(), useStateCountApi()])
		tableLoading.value = true
		await useProjectTimeOutApi()
			.then(res => {
				if (res.code === 0) {
					tableData.value = res.data
				}
			})
			.finally(() => {
				tableLoading.value = false
			})

		// 检查响应状态并处理数据
		handleApiResponse(responses[0], 'projectCount')
		handleApiResponse(responses[1], 'stateCount')
		// handleApiResponse(responses[2], 'projectTimeOut')
		// 数据加载完成后，更新图表
		updateEcharts()
	} finally {
		descLoading.value = false
	}
	console.log(tableData.value)
}

// 处理API响应
const handleApiResponse = (response, dataKey) => {
	if (response.code === 0) {
		switch (dataKey) {
			case 'projectCount':
				try {
					processProjectCount(response.data)
				} catch (error) {
					console.error('处理项目计数数据时发生错误:', error)
				}
				break
			case 'stateCount':
				try {
					stateCount.value = response.data
				} catch (error) {
					console.error('处理项目环节超时数据时发生错误:', error)
				}
				break
			case 'projectTimeOut':
				try {
					const data = response.data
					if (Array.isArray(data)) {
						tableData.value = data
						console.log(tableData.value)
					} else {
						console.error('收到的数据不是数组')
					}
				} catch (error) {
					console.error('处理项目环节超时数据时发生错误:', error)
				}
				break
			default:
				console.warn('未知的数据类型:', dataKey)
		}
	} else {
		console.warn('数据加载失败，错误码:', response.code)
	}
}

// 处理项目计数数据
const processProjectCount = data => {
	source.value = data.projectCount || 0
	projectcompleteCount.value = data.completeCount || 0
	projectUncompleteCount.value = (data.projectCount || 0) - (data.completeCount || 0)
}

// 更新ECharts图表
const updateEcharts = () => {
	if (main.value) {
		const myChart = echarts.init(main.value)
		// 构建图表配置
		const option = buildEchartsOption()

		// 应用图表配置
		myChart.setOption(option)
		myChart.resize()
	}
}

// 构建ECharts图表配置
const buildEchartsOption = () => {
	// 初始化图表配置对象
	let option = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
			}
		},
		grid: {
			right: '20%' // 为右侧的Y轴留出空间
		},
		toolbox: {
			feature: {
				dataView: { show: true, readOnly: false }, // 数据视图工具
				restore: { show: true }, // 恢复默认设置按钮
				saveAsImage: { show: true } // 保存为图片按钮
			}
		},
		legend: {
			data: ['处理中', '已超时', '平均时长'] // 图例
		},
		xAxis: [
			{
				type: 'category',
				axisTick: {
					alignWithLabel: true
				},
				data: [] // X轴数据，稍后填充
			}
		],
		yAxis: [
			{
				type: 'value',
				name: '数量',
				position: 'right' // 数量轴放置在右侧
			},
			{
				type: 'value',
				name: '平均时长（天）',
				position: 'left', // 平均时长轴放置在左侧
				axisLabel: {
					formatter: value => {
						// 将分钟数转换为天数、小时和分钟的格式
						const days = Math.floor(value / (24 * 60))
						const hours = Math.floor((value % (24 * 60)) / 60)
						const minutes = value % 60
						return `${days}天${hours}时${minutes}分`
					}
				}
			}
		],
		series: [
			// 处理中数据系列
			{
				name: '处理中',
				type: 'bar',
				data: []
			},
			// 已超时数据系列
			{
				name: '已超时',
				type: 'bar',
				data: []
			},
			// 平均时长数据系列
			{
				name: '平均时长',
				type: 'line',
				yAxisIndex: 1, // 使用左侧的Y轴
				data: [],
				markPoint: {
					symbolSize: 10,
					data: [] // 标记点数据，稍后填充
				}
			}
		]
	}

	// 从stateCount.value中提取数据
	const categories = stateCount.value.map(item => item.stepName)
	const beingProcessedCountData = stateCount.value.map(item => item.beingProcessedCount)
	const timeoutsCountData = stateCount.value.map(item => item.timeoutsCount)
	const averageDurationData = stateCount.value.map(item => item.averageDuration)

	// 转换平均时长数据为数值，便于绘图
	const averageDurationNumData = averageDurationData.map(durationStr => {
		const match = durationStr.match(/(\d+)天(\d+)时(\d+)分/)
		if (match) {
			const days = parseInt(match[1], 10)
			const hours = parseInt(match[2], 10)
			const minutes = parseInt(match[3], 10)
			return days * 24 * 60 + hours * 60 + minutes
		}
		return 0 // 如果无法解析，默认为0
	})

	// 自定义折线图数据点的显示格式
	const markPoint = {
		symbolSize: 10,
		data: []
	}
	averageDurationNumData.forEach((value, index) => {
		// 将分钟数转换为天数
		const days = Math.floor(value / (24 * 60))
		// 剩余的小时数
		const hours = Math.floor((value % (24 * 60)) / 60)
		// 剩余的分钟数
		const minutes = value % 60
		// 添加标记点数据
		markPoint.data.push({
			coord: [categories[index], value],
			name: `${days}天${hours}时${minutes}分`,
			label: {
				formatter: `${days}天${hours}时${minutes}分`, // 标签显示格式
				position: 'top' // 标签位置
			}
		})
	})

	// 更新图表配置
	option.xAxis[0].data = categories // 更新X轴数据
	option.series[0].data = beingProcessedCountData // 更新处理中数据
	option.series[1].data = timeoutsCountData // 更新已超时数据
	option.series[2].data = averageDurationNumData // 更新平均时长数据
	option.series[2].markPoint = markPoint // 更新标记点数据

	return option
}
</script>
<style lang="scss" scoped>
.home-image {
	width: 100%;
	height: 600px;
	background: url('@/assets/logo.png') no-repeat center center;
}

.user-header {
	width: 100%;
	background-color: #fff;
	margin-bottom: 10px;

	.left-content {
		width: calc(100% - 420px);

		h3 {
			color: rgba(0, 0, 0, 0.75);
		}
	}

	.content {
		display: flex;
		justify-content: space-between;

		.weather {
			width: 400px;
		}
	}

	.last-login-info {
		font-size: 13px;
		color: #333;
		overflow-wrap: break-word;
		padding: 0;
		margin: 1px 0 0 0;
	}

	.sentence {
		display: block;
		font-size: 12px;
		color: #acacac;
		overflow-wrap: break-word;
		padding: 5px 0 0 0;
		margin: 6px 0 0 0;
	}

	.sentence:hover {
		cursor: pointer;
		text-decoration: underline;
	}
}
</style>
